<?php
/**
 * Created by PhpStorm.
 * User: MrDong
 * Date: 2020/6/10
 * Time: 10:41
 */

namespace frontend\controllers;


use backend\models\OrderSearch;
use common\helpers\MoneyHelper;
use common\helpers\SendMsgHelper;
use common\helpers\StringHelper;
use common\models\CarValuation;
use common\models\DiscountCoupon;
use common\models\DiscountCouponInSetMeal;
use common\models\Member;
use common\models\MemberBind;
use common\models\MemberDiscountCoupon;
use common\models\Order;
use common\models\SetMeal;
use common\models\SetMealItems;
use common\models\SetMealOrder;
use frontend\models\MemberDiscountCouponSearch;
use frontend\models\SetMealOrderSearch;
use frontend\models\MemberNoticeSearch;
use common\models\MemberNotice;

class MemberController extends BaseController
{
    /**
     * 二手车估价
     * @throws \Exception
     */
    public function actionCarValuation()
    {
        $model = new CarValuation();
        if($model->load(\Yii::$app->request->post(), "")) {
            $model->member_id = \Yii::$app->user->identity->id;
            $model->created_at = time();
            if(!$model->save()) {
                throw new \Exception("提交异常:" . current($model->getFirstErrors()));
            }
            return true;
        } else {
            throw new \Exception("提交数据异常！");
        }

    }

    /**
     * 我的订单
     *
     * @return array
     */
    public function actionMyOrders()
    {
//        $searchModel         = new OrderSearch();
        $member_id = \Yii::$app->user->identity->id;
//        $dataProvider        = $searchModel->search(\Yii::$app->request->queryParams);
//        $items               = $dataProvider->getModels();
//       return Order::find()->where(['member_id'=>$member_id])->all();

        return Order::find()->with('productInfo')->where(['member_id'=>$member_id])->asArray()->all();
    }

    /*
     * 订单详情
     */
    public function actionMyOrder($id)
    {
        $member_id = \Yii::$app->user->identity->id;
        return Order::find()->with('productInfo')->where(['member_id'=>$member_id,'id'=>$id])->asArray()->one();
    }

    /*
     * 提交订单
     */
    public function actionPostOrder()
    {
        $model= new Order();
        if($model->load(\Yii::$app->request->post(),'')){
            $model->member_id = \Yii::$app->user->identity->id;
            $model->created_at = time();
            if(!$model->save()) {
                throw new \Exception("提交异常:" . current($model->getFirstErrors()));
            }
            return true;
        }else{
            throw new \Exception("提交数据异常！");
        }
    }

     /**
     * 个人信息
     * @return array|\yii\db\ActiveRecord|null
     */
    public function actionUserInfo()
    {
        return Member::find()->with('bindInfo')->where(['id' => \Yii::$app->user->identity->id])->asArray()->one();
    }



    /**
     * 我的优惠券
     * @param $status
     * @return array
     */
    public function actionMyCoupons($status)
    {
        $searchModel         = new MemberDiscountCouponSearch();
        $searchModel->member_id = \Yii::$app->user->identity->id;
        $searchModel->status = $status;
        $dataProvider        = $searchModel->search(\Yii::$app->request->queryParams);
        $items               = $dataProvider->getModels();
        foreach ($items as &$item) {
            $item['created_at'] = date("Y-m-d H:i:s", $item['created_at']);
            $item['discountCoupon']['start_date'] = date("Y-m-d", $item['discountCoupon']['start_date']);
            $item['discountCoupon']['end_date'] = date("Y-m-d", $item['discountCoupon']['end_date']);
        }
        return [
            "lists"      => $items,
            "totalPage" => $dataProvider->pagination->getPageCount()
        ];
    }


    /**
     * 登录
     * @return array
     * @throws \Exception
     */
    public function actionLogin()
    {
        try {
            $data  = \Yii::$app->request->post();
            if($data['type'] == "phone") {
                /* @var $model Member*/
                $model = Member::find()->where(['username' => $data['username']])->one();
                if (!$model) {
                    throw new \Exception("用户名或密码错误！");
                }
                if (!\Yii::$app->security->validatePassword($data['password'], $model->password)) {
                    throw new \Exception("用户名或密码错误！");
                }
                return [
                    "access_token" => $model->generateAccessToken(),
                    "userInfo"     => $model
                ];
            } else {
                $trans = \Yii::$app->db->beginTransaction();
                try {
                    /* @var $model MemberBind*/
                    $model = MemberBind::find()->where(['openid' => $data['openid'], 'type' => $data['type']])->one();
                    if (!$model || !$model->member_id) {
                        throw new \Exception("请先绑定账号登录!", 400001);
                    } else {
                        /* @var  $member Member*/
                        $member = Member::find()->where(['id' => $model->member_id])->one();
                        if (!$member) {
                            throw new \Exception("数据异常!");
                        }
                    }

                    $trans->commit();
                    return [
                        "access_token" => $member->generateAccessToken(),
                        "userInfo"     => Member::find()->where(['id' => $member->id])->with("bindInfo")->asArray()->one()
                    ];
                } catch (\Exception $e) {
                    $trans->rollBack();
                    throw new \Exception( $e->getMessage());
                }
            }
        } catch (\Exception $e) {
            throw new \Exception("登陆失败:" . $e->getMessage());
        }
    }

    /**
     * 绑定登录
     * @return array
     * @throws \Exception
     */
    public function actionBindLogin()
    {
        $data  = \Yii::$app->request->post();
        $trans = \Yii::$app->db->beginTransaction();
        try {
            /* @var $model MemberBind*/
            $model = MemberBind::find()->where(['openid' => $data['openid'], 'type' => $data['type']])->one();
            if(!$model) {
                $member = new Member();
                $member->username = $data['openid'];
                $member->created_at = time();
                $member->updated_at = time();
                if(!$member->save()) {
                    throw new \Exception("注册异常:" . current($member->getFirstErrors()));
                }

                $model = new MemberBind();
                $data = \Yii::$app->request->post();
                $model->openid = $data['openid'];
                $model->nickname = $data['nickname'];
                $model->type = $data['type'];
                $model->avatar = $data['avatar'];
                $model->member_id = $member->id;
                if(!$model->save()) {
                    throw new \Exception("注册绑定异常:" . current($model->getFirstErrors()));
                }
            } elseif(!$model->member_id) {
                /* @var  $member Member*/
                $member = Member::find()->where(['username' => $data['username']])->one();
                if (!$member) {
                    throw new \Exception("用户名不存在或密码错误！");
                }
                if (!\Yii::$app->security->validatePassword($data['password'], $model->password)) {
                    throw new \Exception("用户名不存在或密码错误！");
                }
                if(MemberBind::find()->where(['openid' => $data['openid'], 'type' => $data['type'], 'member_id' => $member->id])->exists()) {
                    throw new \Exception("该账号已被绑定！");
                }

                $model->member_id = $member->id;
                if(!$model->save(false)) {
                    throw new \Exception("绑定账号异常:" . current($model->getFirstErrors()));
                }
            } else {
                throw new \Exception("数据异常!");
            }
            $trans->commit();
            return [
                "access_token" => $member->generateAccessToken(),
                "userInfo"     => Member::find()->where(['id' => $member->id])->with("bindInfo")->asArray()->one()
            ];
        } catch (\Exception $e) {
            $trans->rollBack();
            throw new \Exception( $e->getMessage());
        }
        
    }

      /**
     * 注册
     * @return Member
     * @throws \yii\base\Exception
     */
    public function actionRegister()
    {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $model = new Member();
            $data = \Yii::$app->request->post();
            if($data['code'] != \Yii::$app->cache->get($data['phone'])) {
                throw new \Exception("验证码不正确，请重新输入！");
            }
            $model->username = $data['phone'];
            $model->password = \Yii::$app->security->generatePasswordHash($data['password']);
            $model->created_at = time();
            $model->updated_at = time();

            if(isset($data['invitation_code']) && $data['invitation_code']) {
                $m = Member::findOne(['code' => $data['invitation_code']]);
                if(!$m) {
                    throw new \Exception("无效的邀请码！");
                }
                $model->pid = $m->id;
            }

            $code = StringHelper::randomkeys(6);
            while (Member::find()->where(['code' => $code])->exists()) {
                $code = StringHelper::randomkeys(6);
            }
            $model->code = $code;
            if(!$model->save()) {
                throw new \Exception("注册异常:" . current($model->getFirstErrors()));
            }

            //注册领取新人优惠券
            $couponIds = array_column(DiscountCoupon::find()->where(['is_new' => 1])->all(), "discount_coupon_id");
            $item = new MemberDiscountCoupon();
            foreach ($couponIds as $id) {
                $item->isNewRecord = true;
                $item->id = 0;
                $item->member_id = \Yii::$app->user->identity->id;
                $item->discount_coupon_id = $id;
                $item->created_at = time();
                $item->updated_at = time();
                if(!$item->save()) {
                    throw new \Exception("优惠券领取失败：". current($item->getFirstErrors()));
                }
            }
            $trans->commit();
            return $model;
        } catch (\Exception $e) {
            $trans->rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 发送短信
     * @return bool
     */
    public function actionSendMsg($phone)
    {
        //生成验证码
        $code = rand(100000, 999999);
        \Yii::$app->cache->set($phone, $code);
        //发送短信
        SendMsgHelper::sendMsg($phone, $code);
        return true;
    }

    /**
     * 分享领取优惠券
     * @param $set_meal_id
     * @return bool
     * @throws \Exception
     */
    public function actionShare($set_meal_id)
    {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $model = SetMeal::findOne($set_meal_id);
            if(!$model) {
                throw new \Exception("数据异常！");
            }

            $couponIds = array_column(DiscountCouponInSetMeal::find()->where(['set_meal_id' => $set_meal_id])->all(), "discount_coupon_id");

            $item = new MemberDiscountCoupon();
            foreach ($couponIds as $id) {
                $item->isNewRecord = true;
                $item->id = 0;
                $item->member_id = \Yii::$app->user->identity->id;
                $item->discount_coupon_id = $id;
                $item->created_at = time();
                $item->updated_at = time();
                if(!$item->save()) {
                    throw new \Exception("优惠券领取失败：". current($item->getFirstErrors()));
                }
            }
            $trans->commit();
            return true;
        } catch (\Exception $e) {
            $trans->rollBack();
            throw new \Exception($e->getMessage());
        }
    }
    
    /**
     * 我的消息列表
     * @return array
     */
    public function actionMyNotice()
    {
        $searchModel         = new MemberNoticeSearch();
        $searchModel->member_id = \Yii::$app->user->identity->id;
        $dataProvider        = $searchModel->search(\Yii::$app->request->queryParams);
        $items               = $dataProvider->getModels();
        foreach ($items as &$item) {
            $item['created_at'] = date("Y-m-d H:i:s", $item['created_at']);
            $item['notice']['created_at'] = date("Y-m-d", $item['notice']['created_at']);
        }

        return [
            "lists"      => $items,
            "totalPage" => $dataProvider->pagination->getPageCount()
        ];
    }

    /**
     * 消息详情
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function actionNoticeDetail($id)
    {
        $model = MemberNotice::findOne($id);
        if(!$model) {
            throw new \Exception("数据异常！");
        }
        if($model->is_read == 0) {
            $model->is_read = 1;
            if(!$model->save()) {
                throw new \Exception("标记已读失败：". current($model->getFirstErrors()));
            }
        }
        $item = $model->notice;
        $item->created_at = date("Y-m-d H:i:s", $item->created_at);
        return $item;
    }
    
    
}